<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      :title="
        isUpdate
          ? t('routes.demo.documentManager.modifyDirectory')
          : t('routes.demo.documentManager.addDirectory')
      "
      @register="register"
      @ok="handleSubmit"
      :destroyOnClose="true"
      :minHeight="450"
      :width="600"
    >
      <BasicForm @register="registerForm" />
    </BasicModal>
  </div>
</template>
<script lang="ts" setup>
  import { ref, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getDirectoryModal } from './tableData';
  import { useI18n } from '/@/hooks/web/useI18n';

  import { addPrdFolder, updatePrdFolder } from '/@/api/demo/document';

  const { t } = useI18n();
  const { createMessage } = useMessage();
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const superId = ref('');

  async function handleSubmit() {
    try {
      const values = await validate();
      setModalProps({ confirmLoading: true });
      if (unref(isUpdate)) {
        // 修改
        values['folderId'] = superId.value;
        updatePrdFolder(values).then(() => {
          emit('success');
          createMessage.success(t('common.editSuccessText'));
          closeModal();
        });
      } else {
        // 新增
        values['superId'] = superId.value;
        await addPrdFolder(values).then(() => {
          emit('success');
          createMessage.success(t('common.addSuccessText'));
          closeModal();
        });
      }
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  // 定义弹窗是否可见
  const [register, { setModalProps, closeModal }] = useModalInner((data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    superId.value = data.treeKey === undefined ? '' : data.treeKey;
    if (unref(isUpdate)) {
      setFieldsValue({ ...data.res });
    }
  });

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelCol: { span: 24 },
    wrapperCol: { span: 24 },
    schemas: getDirectoryModal(isUpdate),
    showActionButtonGroup: false,
  });
</script>
<style lang="less" scoped></style>
